#!/bin/sh
#LGPL Barry Kauler 2006,2007 www.puppylinux.com
#v2.14 rc.network now a separate process.
# re-written by Dougal, July 15th 2008 (to work with modified config structure
# Update: 			 add PRIORITY_LIST support
# Update: Jul. 20th: add support for static ip with wireless
# Update: Jul. 23rd: fix bugs reported by Will: testInterface and "ls ..."
# Update: Jul. 25th: add support for "connect" argument, to run after boot
# Update: Jul. 26th: add success/failure messages
# Update: Jul. 28th: add loop for sleeping at bootup
# Update: Jul. 30th: if iwlist scan finds nothing, sleep 1 and try again
#					 add setting of DEBUG_OUTPUT, so it doesn't default to /dev/null
# Update: Aug.  1st: move configuration files into /etc/network-wizard
# Update: Aug. 15th: change "open" to "Open" in wireless profile name...
#					 add "IE:" and "wpa_ie" to SCAN_LIST, for encryption type
#					 add support for start/stop/restart and create stop_all
# Update: Aug. 16th: include Extra: lines in SCAN_LIST, for WPA/WPA2
# Update: Aug. 26th: add gxmessage to wpa_connect
# Update: Sep.  1st: add firewire code
# Update: Sep. 13th: update ath5k exception to use "ath5k*"
# Update: Sep. 15th: disable bringing interface down/up when setting static ip
#					 add "dev $INTERFACE" to route commands
#					 disable exiting on successful connection -- to allow more than 1 interface
# Update: Sep. 16th: replace all `` subshells with $()
# Update: Sep. 20th: add GOT_ONE="yes", for dialog at end (since not exiting anymore)
# Update: Sep. 24th: add killing wpa_supplicant it validation fails!
#					 use updated useWpaSupplicant instead of wpa_connect
#					 add killing dhcpcd if it returns error (it daemonizes even if error)
#					 use "stop_all -a" to do all the cleanup at the top
# Update: Sep. 25th: use the new setupDHCP for dhcp setup
# Update: Oct.  1st: add reloading of bcm43xx, since it seems to not work well otherwise 
# Update: Oct.  5th: add definition of PATH, in case we're run by acpid etc.
#					 change sleep between ifplugstatus tests to 2sec (like wiz)+ add ethtool
# Update: Oct. 18th: add an extra "sleep 10" for pcmcia NICs to initialize (if they exist...)
# Update: Oct. 26th: add localization (only for gui messages)
# Update: Oct. 28th: move the "stop_all -a" to after the "if [ "$ACTION" = "restart" ]"
# Update: Oct. 31st: check for locale files both of type "ab_CD" and "ab"
#					 move the route table flushing into stop_all
# Update: Nov.  7th: add deleting old backups of resolve.conf
# Update: Nov. 28th: remove bashism
# Update: Dec. 10th: add "sleep 1" at the beginning of testInterface (rerwin's fix)
# Update: Feb. 8th '09: implement suggestion from OldTxPup: ifconfig down/up after scanning
#					 in stop_all, skip interfaces with wake-on-lan enabled
#					 move iwlist code into a function, run_iw_scan, and add ejecting pcmcia
# Update: Feb. 22nd: change the backing up of resolve.conf so it only saves as resolv.conf.old
# Update: Mar. 19th: change to using tmp files for wireless scans (try and get max networks)
# Update: Mar. 26th: add 5 second sleep between wireless scans for pcmcia cards
# Update: Mar. 29th: move (pcmcia) 5 second sleep to start if run_iw_scan
# Update: Apr.  1st: change pcmcia sleep detection to module name being *_cs...
# Update: Apr.  2nd: fix finding profiles in prism case, add checkIsPCMCIA
#091108 BK old ifplugstatus renamed to ifplugstatus-0.18.
#
# shinobar
# 29nov09: rewrite eth0 mac address by shinobar
#  9feb10: avoid removing exist HARDWARE.conf, reset interface before rewriting
# 20feb10: old and new ifplugstatus, moved rewriting eth0 mac address
# 25feb10: fix was success message even setupDHCP failed, exit if one interface successed
#  7mar10: stop even wake-on-lan enabled
# 31may12: wait eth0 reday
# 22apr2014: more delay at scan (run_iw_scan)
#  5mar2017: improve check of iwscan*.tmp for reliability; improve success/fail message size & timeout
# 9mar2017: ensure current exec name set
#170612 verify wifi country of regulation matches user specified country.

######### TODO ###########
#- need to find out about static ip... can we check somehow (arp)? maybe use
#  dhcpcd if it fails? (do we know if it fails?)
#- let user prioritise networks/interfaces?
#- might want to add something to check if interface is connected already
# (for running with the "restart" option)

# Add this to support standard arguments, while being compatible with Puppy
case $1 in
  stop) ACTION="stop" ;;
  connect|restart) ACTION="restart" ;;
  start|*) ACTION="start" ;; # also supports no args
esac

# Add path, in case it is run by acpid or such
PATH=/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/bin

# basic configuration info for interface
# named $HWADDRESS.conf (assuming the HWaddress is more unique than interface name...)
# mainly intended to know if interface has been "configured"...
NETWORK_INTERFACES_DIR='/etc/network-wizard/network/interfaces'
DEBUG_OUTPUT=/dev/stderr

# Dougal: add localization
mo=net-setup.mo
#lng=${LANG%.*}
# always start by sourceing the English version (to fill in gaps)
. "/usr/share/locale/en/LC_MESSAGES/$mo"
if [ -f "/usr/share/locale/${LANG%.*}/LC_MESSAGES/$mo" ];then
  . "/usr/share/locale/${LANG%.*}/LC_MESSAGES/$mo"
elif [ -f "/usr/share/locale/${LANG%_*}/LC_MESSAGES/$mo" ];then
  . "/usr/share/locale/${LANG%_*}/LC_MESSAGES/$mo"
fi

#  Dougal: want to use functions from wag-profiles (cleanUpInterface...)
#+ so source it 
. /usr/sbin/wag-profiles.sh

# A function to stop everything (at shutdown, for example)
# Enable accepting a param to pass to ifconfig (i.e. -a)
stop_all(){
	for INTERFACE in $(ifconfig $1 | grep -F 'Link encap:Ethernet' | cut -f 1 -d " ") ; do
		# Skip it wake-on-lan enabled # 7mar10 stop even wake-on-lan enabled
		#ethtool $INTERFACE | grep -Fq 'Wake-on: g' && continue
		# clean up (kills dhcpcd, wpa_supplicant etc.)
    	cleanUpInterface "$INTERFACE" >/dev/null 2>&1
    	ip route flush dev "$INTERFACE"
    	ifconfig "$INTERFACE" down
  	done
}

# Dougal: add option to run with "stop" at shutdown... 
# (will enable to add things in the future)
if [ "$ACTION" = "stop" ] ; then
  stop_all
  exit
fi

# A couple of dialog messages to notify of sucess or failure
success_message(){
	if [ "$HAVEX" = "yes" ]; then 
	  gxmessage -center -font "sans 16" -geometry 200x100 -borderless -timeout 5 -bg "green" -buttons "" -title "$L_TITLE_Success" "
      $L_MESSAGE_Success!   " & # 5mar2017
	else
	  echo "$L_MESSAGE_Success!"
	fi
}
	
failure_message(){
	if [ "$HAVEX" = "yes" ]; then 
	  gxmessage -center -font "sans 16" -geometry 200x100 -borderless -timeout 5 -bg "red" -buttons "" -title "$L_TITLE_Failure" "
         $L_MESSGAE_Failed.   " & # 5mar2017
	else
	  echo "$L_MESSGAE_Failed..."
	fi
}

# cutdown version of this function (can't just source net-setup.sh...)
testInterface()
{
  #INTERFACE="$1"
  echo -n "checking if interface $INTERFACE is alive..."
  #sleep 1 # rerwin's original solution
  # no, move the sleep 1 so is only used for wireless
  #091108 old ifplugstatus now -0.18, latest is just 'ifplugstatus'...
  IFPLUGOLD=ifplugstatus
  IFPLUGNEW=ifplugstatus
  [ -x /sbin/ifplugstatus-0.18 ] && IFPLUGOLD=ifplugstatus-0.18
  [ -x /sbin/ifplugstatus-0.25 ] && IFPLUGNEW=ifplugstatus-0.25
  if ! $IFPLUGOLD "$INTERFACE" | grep -F -q 'link beat detected' ;then
    sleep 1
    if ! $IFPLUGNEW "$INTERFACE" | grep -F -q 'link beat detected' ;then
      sleep 2
      if ! $IFPLUGOLD "$INTERFACE" | grep -F -q 'link beat detected' ;then
        sleep 2
        if ! $IFPLUGNEW "$INTERFACE" | grep -F -q 'link beat detected' ;then
          # add ethtool test, just in case it helps at times...
          sleep 1
          if ! ethtool "$INTERFACE" | grep -Fq 'Link detected: yes' ; then
		    echo "no"
		    return 1
		  fi
        fi
      fi
    fi
  fi
  echo "yes"
  return 0
} # end of testInterface

# cutdown version of this function (can't just source net-setup.sh...)
# config file will include IP_ADDRESS, NETMASK, DNS_SERVER[12], GATEWAY
setupStaticIP()
{
	BROADCAST=$(ipcalc -b "$IP_ADDRESS" "$NETMASK" | cut -d= -f2)
	echo "configuring interface $INTERFACE with static ip..."
	#ifconfig "$INTERFACE" down
	
	# do the work
	ifconfig "$INTERFACE" "$IP_ADDRESS" netmask "$NETMASK" broadcast "$BROADCAST" #up
	if [ $? -eq 0 ];then
		# Configure a nameserver, if we're supposed to.
		# This now replaces any existing resolv.conf, which
		# we will try to back up.
		if [ "$DNS_SERVER1" != "0.0.0.0" ] ; then
			# remove old backups
			rm /etc/resolv.conf.[0-9][0-9]* 2>/dev/null
			# backup previous one
			mv -f /etc/resolv.conf /etc/resolv.conf.old
			echo "nameserver $DNS_SERVER1" > /etc/resolv.conf
			if [ "$DNS_SERVER2" != "0.0.0.0" ] ; then
				echo "nameserver $DNS_SERVER2" >> /etc/resolv.conf
			fi
		fi
	
		# add default route, if we're supposed to
		if [ "$GATEWAY" ] ; then
			route add -net default gw "$GATEWAY" #dev $INTERFACE
			if [ $? -eq 0 ];then #0=ok.
				echo "Default route set through $GATEWAY."
			else
				echo -e "Could not set default route through $GATEWAY.  Please try again.\nNote that Puppy has tried to do this:\nroute add -net default gw $GATEWAY" #dev $INTERFACE"
				#ifconfig "$INTERFACE" down
				return 1
			fi
		fi
		
		return 0
	else
		echo -e "Interface configuration failed; please try again.\nWhat Puppy has just tried to do is this:\nifconfig $INTERFACE $IP_ADDRESS netmask $NETMASK broadcast $BROADCAST up"
		#ifconfig "$INTERFACE" down
		return 1
	fi
} #end of setupStaticIP

#  Dougal: stick the wireless scan into a function, since we're doing some tricks
#+ to try and ensure it works...
run_iw_scan(){
	# add sleeping a bit for pcmcia...
	#grep -q "^pcmcia:" /sys/class/net/$INTERFACE/device/modalias &&	sleep 5
	#case $INTMODULE in *_cs) sleep 5 ;; esac
	#checkIsPCMCIA
	#[ -n "$IsPCMCIA" ] && sleep 5
	# no try runing twice and redirecting to files, then use bigger one...
	# clean up any old files
	rm /tmp/iwscan*.tmp 2>/dev/null
	#shinobar: more wait
	W=1
	for HOTOKE in $(seq 3); do
	  sleep $W
	  iwlist "$INTERFACE" scan >/tmp/iwscan1.tmp 2>&1
	  grep -q 'Scan completed' /tmp/iwscan1.tmp && break
	  W=$(($W * 2))
	done
	sleep 1
	#shinobar: more wait END
	#if [ -n "$IsPCMCIA" ] ; then
	#  sleep 1
	#else
	#  usleep 100000
	#fi
	iwlist "$INTERFACE" scan >/tmp/iwscan2.tmp 2>&1
#	ScanListFile=$(du -b /tmp/iwscan*.tmp |sort -n | tail -n1 |cut -f2)
	ScanListFile=$(ls -1 /tmp/iwscan*.tmp | sort -V | tail -n 1) # 5mar2017
	# now try scanning
	#SCAN_LIST=$(iwlist "$INTERFACE" scan | grep 'Cell\|ESSID\|Mode\|Frequency\|Encryption\|Channel')
	#SCAN_LIST=$(grep 'Cell\|ESSID\|Mode\|Frequency\|Encryption\|Channel' $ScanListFile)
	#rm /tmp/iwscan*.tmp
	## no, use the file all the time, so just get the cell list
	CELL_LIST=$(grep -Eo "Cell [0-9]+" $ScanListFile | cut -f2 -d " ")
	# if it failed, try sleeping and trying again
	#if [ -z "$SCAN_LIST" ] ; then
	if [ -z "$CELL_LIST" ] ; then
		# with pcmcia try ejecting and inserting (this is done in wag-profiles.sh)
		if [ -n "$IsPCMCIA" ] ; then
			pccardctl eject
			pccardctl insert
			sleep 1
		fi
		sleep 1
		#SCAN_LIST=$(iwlist "$INTERFACE" scan | grep 'Cell\|ESSID\|Mode\|Frequency\|Encryption\|Channel')
		iwlist "$INTERFACE" scan >/tmp/iwscan3.tmp 2>&1
		ScanListFile="/tmp/iwscan3.tmp"
		CELL_LIST=$(grep -Eo "Cell [0-9]+" $ScanListFile | cut -f2 -d " ")
	fi
}

# function like assignProfileData, but for use with CELL_* for open networks
cellToProfile(){
	# assign to PROFILE_ names...
	PROFILE_ESSID="$CELL_ESSID"
	PROFILE_FREQ="$CELL_FREQ"
	PROFILE_CHANNEL="$CELL_CHANNEL"
	PROFILE_AP_MAC="$CELL_AP_MAC"
	PROFILE_MODE="$CELL_MODE"
	PROFILE_NWID=""
	PROFILE_KEY=""
} # cellToProfile

# function to get ip address, via static ip or dhcp
try_and_connect(){
	local RETURN=1
	if [ "$STATIC_IP" = "yes" ] ; then # static ip address 
	  if setupStaticIP ; then
	    # need to quit, probably
	    RETURN=0
	  fi
    else
      setupDHCP #|| killDhcpcd "$INTERFACE" # 25feb10 
      RETURN=$?
	fi
	return $RETURN
}

# 29nov by shinobar # 9feb10 do not remove $HWADDRESS.conf
rewrite_mac_address () {
  cat /etc/NETWORKING 2>/dev/null | grep -q -i 'yes' || return
  INTERFACES=/etc/network-wizard/network/interfaces
  HWADDRESS=$(LANG=C ifconfig eth0 | head -n 1 | tr -s ' ' | cut -d' ' -f5)
  [ "$HWADDRESS" != "" ] || return
     TMPFILE=/tmp/$(basename $0)_conf.tmp
     rm -f "$TMPFILE"
     IFCONFIG=$(ifconfig)
     CONFS=$(find "$INTERFACES" -follow -type f -name '*.conf' -printf "%P ")
     if [ "$CONFS" != "" ]; then
       for F in $CONFS; do
         echo "$IFCONFIG"|grep -q "$(basename $F .conf)" && continue
         [ ! -f "$TMPFILE" ] && \
           grep -q '^[[:blank:]]*STATIC_IP=.*yes' "$INTERFACES/$F" && \
           cp "$INTERFACES/$F" "$TMPFILE"
         #rm -f "$INTERFACES/$F"
       done
     fi
     [ -f "$TMPFILE" ] && mv -f "$TMPFILE" "$INTERFACES/$HWADDRESS.conf" || \
       echo "IS_WIRELESS=''" > "$INTERFACES/$HWADDRESS.conf"
}

# Dougal: when running after boot, we don't need this
if [ "$ACTION" = "restart" ] ; then # connect
  pidof X >/dev/null && HAVEX="yes"
  exec 1>/tmp/network-connect.log 2>&1
else # below only done at boot
  [ -f /root/.connectwizardrc ] \
   || echo 'CURRENT_EXEC=net-setup.sh' > /root/.connectwizardrc # 9mar2017
  [ -x /usr/sbin/connectwizard_crd ] && connectwizard_crd #170612
  ifconfig lo 127.0.0.1
  route add -net 127.0.0.0 netmask 255.0.0.0 lo
  #rewrite_mac_address  # 9feb10 moved
  # Dougal: add reloading of bcm43xx
  if grep -Fq bcm43xx /proc/modules ; then
    rmmod bcm43xx
    sleep 1
    modprobe bcm43xx
    sleep 1
  fi
  # Wait a bit, so rc.local and profile finish (subtract 1 from MAXWAIT)
  #sleep 1
  #/etc/ethernetmodules has extra modules to load, 
  if [ -s /etc/ethernetmodules ];then #-s tests file not zero size.
    echo "Loading extra ethernet driver modules..."
    #each line of ethernetmodules has a module plus optional params...
    # Dougal: use read to get both
    {
    	read EMODULE
    	read FMODULE
	}</etc/ethernetmodules
    echo "loading $EMODULE module"
    modprobe $EMODULE
    if [ "$EMODULE" != "$FMODULE" ];then
      echo "loading $FMODULE module"
      modprobe $FMODULE
    fi
  fi
  stop_all -a >/dev/null 2>&1	# 9feb10: reset before sense
   # wait up to MAXWAIT seconds, in case some firmware is slow to load
  MAXWAIT=12
  # a list of all the interface config files
  # 31may12: wait eth0 (to be auto configured) reday
  echo -n "Waiting for interfaces to initialize..."
  CONFIGURED=$(cd $NETWORK_INTERFACES_DIR ; ls -1 *.conf 2>/dev/null |cut -d '.' -f1)
  for I in $(seq 1 $MAXWAIT) ; do
    EXIST=$(ifconfig -a | grep -F 'Link encap:')
    for ONE in eth0 $CONFIGURED ; do
      # see if it is detected
      case $EXIST in 
        *$ONE*) ;; # ok
        *) sleep 1 ; echo -n '.' ; continue 2 ;; # go to the next I 
      esac
    done
    # we only get here if all the configured interfaces are found...
    break
  done
  # "close" the line started before the loop
  echo
  # add an extra wait for pcmcia NICs to initialize
  #case "$(cat /sys/class/net/*/device/modalias)" in *pcmcia:*)
  #  echo "pcmcia NIC detected, sleeping an extra 10 seconds"
  #  sleep 10
  #  ;;
  #esac

fi # if [ "$ACTION" = "restart" ] ; then

#  It appears that "cleaning up" an interface, while another one is already
#+ configured with dhcpcd running, somehow messes up the ok interface...
#+ so do all the cleaning at the beginning (note the -a for ifconfig)
#  (this replaces the cleanUpInterface at the start of the big loop)

rewrite_mac_address  # 20feb10 moved here
stop_all -a >/dev/null 2>&1

GOT_ONE=""
# Dougal: read everything, so we get HWaddress, too
while read INTERFACE A B C HWADDRESS
do
  if [ "$B" = "encap:UNSPEC" ] ; then
	# check if it's firewire...
	[ "$(cat /sys/class/net/$INTERFACE/type)" = "24" ] || continue
  elif [ "$B" != "encap:Ethernet" ] ; then
    continue
  fi
  echo "configuring network interface $INTERFACE"
  if [ "$C" != "HWaddr" -o -z "$HWADDRESS" ] ; then
    echo "interface $INTERFACE does not seem to have a HWaddress... skipping"
    continue
  fi
  # see if already "configured"
  if [ ! -f "${NETWORK_INTERFACES_DIR}/$HWADDRESS.conf" ] ; then
    echo "interface $INTERFACE has not been configured... skipping"
    continue
  fi
  # clean up, skip if fails (=ifconfig up failed)
  ## cleanup moved to top, just raise here.
  if ! ifconfig "$INTERFACE" up ; then
    echo "failed to raise interface $INTERFACE... skipping"
    continue
  fi
  
  # unset static ip variables
  unset STATIC_IP IP_ADDRESS NETMASK DNS_SERVER1 DNS_SERVER2 GATEWAY
  
  # source config
  . "${NETWORK_INTERFACES_DIR}/$HWADDRESS.conf"
  
  # see if it's wireless
  if [ -f "${WLAN_INTERFACES_DIR}/$HWADDRESS.conf" ] ; then
    OPEN_NETWORKS=""
    USE_WLAN_NG=""
    # we need the driver name, in case it's ath5k
    INTMODULE=$(readlink /sys/class/net/$INTERFACE/device/driver)
    INTMODULE=${INTMODULE##*/}
    . "${WLAN_INTERFACES_DIR}/$HWADDRESS.conf"
    # this should tell us if to use wlan_ng etc.
    if [ "$USE_WLAN_NG" = "yes" ] ; then ####### use wlanctl-ng ########
      if runPrismScan "$INTERFACE" ; then #>/dev/null 
        # go over access points (POINTNUM set in function)
        for P in $(seq 0 $POINTNUM) ; do
          grep -Fq 'resultcode=success' /tmp/prism-scan$P || continue
	      getPrismCellParameters $P
          # we should have CELL_ESSID, CELL_CHANNEL, 
          # CELL_AP_MAC, CELL_MODE, CELL_ENCRYPTION
          # see if access point configured
          #### need to see about the ecryption part: gives "true" or "no_value"
		  case $CELL_ENCRYPTION in
		    true) CELL_ENCRYPTION=WEP ;;
		    *) CELL_ENCRYPTION=Open ;;
		  esac
		  if [ -f "${PROFILES_DIR}/${CELL_AP_MAC}.${CELL_ENCRYPTION}.conf" ] ; then
            # unset static ip variables
            unset STATIC_IP IP_ADDRESS NETMASK DNS_SERVER1 DNS_SERVER2 GATEWAY
            # source it
            . "${PROFILES_DIR}/${CELL_AP_MAC}.${CELL_ENCRYPTION}.conf"
            assignProfileData
            # try connection
            if useWlanctl && sleep 1 && testInterface ; then
              # sleep a bit, just in case (net-setup.sh has 5 seconds!)
              #sleep 1
              # try and get ip address
              if try_and_connect ; then
                # done! stop everything. 
                rm /tmp/wlan-up /tmp/prism-* >/dev/null 2>&1
                success_message
                #exit
                # move to next interface (to allow more than one)
                GOT_ONE="yes"
                continue 2
              else
                failure_message
              fi
            elif [ "$CELL_ENCRYPTION" = "Open" ] ; then # add to list of open networks
              OPEN_NETWORKS="$OPEN_NETWORKS $P"
            else # failure of useWlanctl
              failure_message
            fi #if useWlanctl &&
          fi #if [ -f "${PROFILES_DIR}/${CELL_AP_MAC}.${CELL_ENCRYPTION}.conf" ] ; then
        done # for P in
        # if we got here, we are not connected yet, look at open networks
        if [ -n "$OPEN_NETWORKS" ] ; then
          WLAN_SECURE="opensystem"
          PROFILE_KEY=""
          # unset static ip variables
          unset STATIC_IP IP_ADDRESS NETMASK DNS_SERVER1 DNS_SERVER2 GATEWAY
          for P in $OPEN_NETWORKS ; do
            grep -Fq 'resultcode=success' /tmp/prism-scan$P || continue
            getPrismCellParameters $P
            # set the PROFILE_ variables
            PROFILE_ESSID="$CELL_ESSID"
            if useWlanctl && sleep 1 && testInterface ; then
              # sleep a bit, just in case (net-setup.sh has 5 seconds!)
              #sleep 1
              # try and get ip address
              if try_and_connect ; then
                # done! stop everything. 
                rm /tmp/wlan-up /tmp/prism-* >/dev/null 2>&1
                success_message
                #exit
                # move to next interface (to allow more than one)
                GOT_ONE="yes"
                continue 2
              else
                failure_message
              fi
            else # failure of useWlanctl
              failure_message
            fi
          done
        fi
        rm /tmp/wlan-up /tmp/prism-* >/dev/null 2>&1
      else
        echo "wireless scan with wlanctl-ng failed... skipping interface"
        # clean up (kills dhcpcd etc)
        cleanUpInterface "$INTERFACE"
        ifconfig "$INTERFACE" down
        # go to next interface
        continue
      fi # if runPrismScan
    
    else #################### use the usual iwconfig ####################
	  # scan for available networks
	  run_iw_scan
	  #if [ -n "$SCAN_LIST" ]; then
	  if [ -n "$CELL_LIST" ]; then
		#  Dougal: something odd. seems like (at least with some drivers), we
		#+ need to "refresh" after scanning...
		ifconfig "$INTERFACE" down
		ifconfig "$INTERFACE" up
		#CELL_LIST=$(echo "$SCAN_LIST" | grep -Eo "Cell [0-9]+" | cut -f2 -d " ")
        # let the user create a priority list of which networks to use first
        # (will be included in wireless config file, contains mac addresses)
        if [ "$PRIORITY_LIST" ] ; then
          PRIOR_CELLS=""
          for ONE in $PRIORITY_LIST ; do
            # see if it was found, then move cell number to start...
            #ACELL=$(echo "$SCAN_LIST" | grep -F "Address: $ONE" | awk '{print $2}')
			ACELL=$(grep -F "Address: $ONE" $ScanListFile | awk '{print $2}')
            if [ "$ACELL" ] ; then
              PRIOR_CELLS="$PRIOR_CELLS $ACELL"
              # remove from cell list (BASHISM!)
              #CELL_LIST=${CELL_LIST/$ACELL/}
			  CELL_LIST=$(echo "$CELL_LIST" | sed "s/$ACELL//")
            fi
          done
          CELL_LIST="$PRIOR_CELLS $CELL_LIST"
        fi
        for CELL in $CELL_LIST ; do
          Get_Cell_Parameters $CELL
          # we should have at least some of: 
          # CELL_ESSID, CELL_FREQ, CELL_CHANNEL, CELL_QUALITY, 
          # CELL_AP_MAC, CELL_MODE, CELL_ENCRYPTION
          # see if it's open or not
          if [ "$CELL_ENCRYPTION" = "on" ] ; then
            # get only encrypted profiles (might have problems with globbing?)
            for PROF in $(ls ${PROFILES_DIR}/${CELL_AP_MAC}.W[EP][PA]*.conf 2>/dev/null) ; do
              SUCCESS=""
              # unset static ip variables
              unset STATIC_IP IP_ADDRESS NETMASK DNS_SERVER1 DNS_SERVER2 GATEWAY
              # source it
              . "$PROF"
              # assign to PROFILE_ names... 
              assignProfileData
              case $PROFILE_ENCRYPTION in
                WPA|WPA2) 
                  WPA_CONF="${WPA_SUPP_DIR}/${PROFILE_AP_MAC}.${PROFILE_ENCRYPTION}.conf"
                  useWpaSupplicant "$WPA_CONF" && SUCCESS="yes" 
                  ;;
                WEP) 
                  useIwconfig && SUCCESS="yes" 
                  ;;
              esac
              if [ "$SUCCESS" = "yes" ] && sleep 1 && testInterface ; then
                # sleep a bit, just in case (net-setup.sh has 5 seconds!)
                #sleep 1
                # try and get ip address
                if try_and_connect ; then
                  # done! stop everything.
                  success_message
				  # clean scan files
				  rm /tmp/iwscan*.tmp 2>/dev/null
                  #exit
                  # move to next interface (to allow more than one)
                  GOT_ONE="yes"
                  continue 3
                else
                  failure_message
                fi
              else # iwconfig/wpa_supp failed
                failure_message
              fi
            done # for PROF in
          else # encryption off
            # see if it was configured
            if [ -f "${PROFILES_DIR}/${CELL_AP_MAC}.Open.conf" ] ; then
              # unset static ip variables
              unset STATIC_IP IP_ADDRESS NETMASK DNS_SERVER1 DNS_SERVER2 GATEWAY
              # source it
              . "${PROFILES_DIR}/${CELL_AP_MAC}.Open.conf"
              # assign to PROFILE_ names... 
              assignProfileData
              # try connection
              if useIwconfig && sleep 1 && testInterface ; then
                # sleep a bit, just in case (net-setup.sh has 5 seconds!)
                #sleep 1
                # try and get ip address
                if try_and_connect ; then
                  # done! stop everything.
                  success_message
				  # clean scan files
				  rm /tmp/iwscan*.tmp 2>/dev/null
                  #exit
                  # move to next interface (to allow more than one)
                  GOT_ONE="yes"
                  continue 2
                else
                  failure_message
                fi
              else
                failure_message
              fi
            else # add to list of open networks
              OPEN_NETWORKS="$OPEN_NETWORKS $CELL"
            fi
          fi # if [ "$CELL_ENCRYPTION" = "on" ] ; then  
        done # for CELL in
        # if we got here, we are not connected yet, look at open networks
        if [ "$OPEN_NETWORKS" ] ; then
          # unset static ip variables
          unset STATIC_IP IP_ADDRESS NETMASK DNS_SERVER1 DNS_SERVER2 GATEWAY
          for CELL in $OPEN_NETWORKS ; do
            Get_Cell_Parameters $CELL
            # need to convert to PROFILE_...
            cellToProfile
            if useIwconfig && sleep 1 && testInterface ; then
              # sleep a bit, just in case (net-setup.sh has 5 seconds!)
              #sleep 1
              # try and get ip address
              if try_and_connect ; then
                success_message
				# clean scan files
				rm /tmp/iwscan*.tmp 2>/dev/null
                #exit
                # move to next interface (to allow more than one)
                GOT_ONE="yes"
                continue 2
              else
                failure_message
              fi
            else
              failure_message
            fi
          done #for CELL in $OPEN_NETWORKS
        fi
      else # if [ -n "$CELL_LIST" ]; then
        echo "wireless scan with iwlist failed (no networks found)... skipping interface"
        # clean up (kills dhcpcd etc)
        cleanUpInterface "$INTERFACE"
        ifconfig "$INTERFACE" down
		# clean scan files
		rm /tmp/iwscan*.tmp 2>/dev/null
        # go to next interface
        continue
      fi
    fi
    # if we got here, config file exists, but nothing worked
    echo "failed to configure wireless interface $INTERFACE... skipping"
    ifconfig "$INTERFACE" down
    continue
  fi # if [ -f "${WLAN_INTERFACES_DIR}/$HWADDRESS.conf" ] ; then
  # if we got here, it's probably not wireless
  # try and get ip address
  if testInterface ; then
    # sleep a bit, just in case (net-setup.sh has 5 seconds!)
    #sleep 1
    # try and get ip address
    if try_and_connect ; then
      success_message
      exit	# 25feb10
      # move to next interface (to allow more than one)
      GOT_ONE="yes"
      continue
    else
      failure_message
    fi
  else 
    echo "interface $INTERFACE does not seem to be plugged in... skipping"
    ifconfig "$INTERFACE" down
    continue
  fi
  # if we got here, nothing worked, clean up
  # clean up (kills dhcpcd etc)
  cleanUpInterface "$INTERFACE"
  ifconfig "$INTERFACE" down
done<<EOF
$( ifconfig -a | grep -F 'Link encap:' )
EOF

#  if we got here and have x, it means we're running with the "connect"
#+ argument and couldn't connect -- maybe no interfaces have been configured yet
if [ "$HAVEX" = "yes" ] && [ "$GOT_ONE" != "yes" ] ; then 
  gxmessage -center -default "okay" -bg "orange" -title "$L_TITLE_Network_Wizard" "$L_MESSAGE_Failed_To_Connect"
fi

exit
